package com.ag.lzw.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ag.bean.TbDeptType;
import com.ag.bean.TbTask;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserDept;
import com.ag.common.BaseAction;
import com.ag.common.EventUtil;
import com.ag.common.IPermissionService;
import com.ag.contactTree.service.LocalTreeService;
import com.ag.lwc.service.FindfDepService;
import com.ag.lzw.dao.LzwTaskDAO;
import com.ag.lzw.dao.LzwTbEventDAO;
import com.ag.lzw.dao.LzwTbProposeDAO;
import com.ag.lzw.service.GetDeptInTask;
import com.ag.lzw.service.IdentifyService;
import com.ag.lzw.vo.DeptInfo;
import com.ag.lzw.vo.DeptPeople;
import com.ag.lzw.vo.SubDept;
import com.ag.zhh.vo.UserDept;
import com.ag.zhh.vo.UserDeptContact;

@Scope("prototype")
@Controller("getTaskDeptAction")
public class GetTaskDeptAction extends BaseAction implements SessionAware {

	private static final long serialVersionUID = -7193493137933611126L;

	private static final Logger logger = Logger
			.getLogger(GetTaskDeptAction.class);

	@Resource(name = "getDeptInTaskImpl")
	private GetDeptInTask taskDept;
	@Resource(name = "lzwTbEventDAO")
	private LzwTbEventDAO eventDAO;
	@Resource(name = "LocalTreeService")
	private LocalTreeService lts;
	@Resource(name="lzwTbProposeDAO")
	LzwTbProposeDAO proposeDAO;
	@Resource(name="lzwTaskDao")
	private LzwTaskDAO taskDAo;
	@Resource(name="FindfDepService")
	private FindfDepService findDeptSer;
    @Resource(name="IdentifyServiceImpl")
    private IdentifyService identifyServ;

	/**
	 * 调用权限服务逻辑组件
	 */
	@Resource(name = "PermissionServiceImpl")
	private IPermissionService pms;
	/**
	 * 提供Map<String, Object>类型的Session变量，用来保存Struts2注入的Session上下文
	 */
	private Map<String, Object> sessionMap;
	/**
	 * 用户信息返回载体
	 */
	private TbUser tbUser;

	@Override
	public void setSession(Map<String, Object> session) {
		this.sessionMap = session;
	}

	/**
	 * 返回的结果集，查询的部门信息
	 */
	private List<DeptInfo> deptInfos;

	/**
	 * 传入的参数，部门ID
	 * */
	private Map<String, String> deptOption;

	/**
	 * 返回的结果集，属于某个部门的所有员工
	 * */
	private List<DeptPeople> peoples;
	/**
	 * 返回的错误信息
	 */
	private String errMsg;
	
	private List<TbDeptType> deptTypes;

	private List<TbUserDept> userDepts;
	
	private List<DeptPeople> deptPeoples;

	/**
	 * 获取下级部门的部门类型ID
	 */
	private String dtId;
	/**
	 * 部门ID
	 */
	private String Did;
	/**
	 * 查找区局部门下部门和人员的返回vo
	 */
	private List<SubDept> depts;
	/**
	 * 查找区局部门下部门和人员的返回vo
	 */
	private List<UserDeptContact> users;
	
	private String tid;
	private DeptPeople deptpeople;

	/**
	 * 根据部门类型，查找任务分派的顶级部门信息 
	 * @return
	 */
	public String findAllDeptType(){
		List<TbDeptType> result = new ArrayList<TbDeptType>();
		List<TbDeptType> list = this.lts.findDeptType();
		for(int i=0;i < list.size();i++){
			TbDeptType tdt = list.get(i);  
			if(tdt.getDtId().equals("0000")){ //选择药监内部部门，滤掉其他部门
				result.add(tdt);        
				break;
			}
		}
		deptTypes = result;
		logger.info("DeptTypes numbers is "+deptTypes.size());
		return "findAllDeptType";
	}
	
	/**
	 * 根据当前用户的信息，和所选的部门类型，查找其负责的部门信息  
	 * @return
	 */
	public String findUserDeptByDtId(){
		boolean isleader = isCurrentLeader();
		logger.info("Is current user a leader?--"+isleader);
		if(isleader){
			//部门类型id查询部门
			List<TbUserDept> uds = this.lts.findBydeptType(dtId);
			logger.info("the length of UserDept found is:"+uds.size());
			List<TbUserDept> result = new ArrayList<TbUserDept>();
			for(int i=0;i<uds.size();i++){
				TbUserDept ud = uds.get(i);
				//过滤当前部门的子部门,只选出区据部门
				if(ud.getTbUserDept()!=null){
					logger.info("dept fid:"+ud.getTbUserDept().getUdId());
				}
				//取出该用户所管理的部门，并过滤其中部门ID为DI000000000 ，的父级部门
				if(ud.getTbUserDept()!=null && ud.getTbUserDept().getUdId().equals("DI000000000 ")){  
					if(ud.getTbUser()!=null){  //过滤没有负责人的部门
						result.add(ud);
					}
				}
			}
			logger.info("the length of result found is:"+result.size());
			List<DeptPeople> dps = new ArrayList<DeptPeople>();
			for(TbUserDept ud : result){
				DeptPeople dp = new DeptPeople();
				dp.setId(ud.getTbUser().getUId());
				dp.setName(ud.getUdName());
				dp.setDeptID(ud.getUdId());
				dps.add(dp);
			}
			logger.info("the length of deptPeoples is:"+dps.size());
			errMsg="0";
			deptPeoples = dps;
			
		} else {
			TbUser currentUser = this.pms.getCurrentUser(sessionMap);
			// 获取当前用户ID
			String uid = currentUser.getUId(); 
			logger.info("the current user id is:"+uid);
			//部门类型id查询部门
			List<TbUserDept> uds = this.lts.findBydeptType(dtId);
			
			List<TbUserDept> resultDept = new ArrayList<TbUserDept>();
			for(TbUserDept ud :uds ){
				if(ud.getTbUser()!=null){
					//匹配遍历的部门的负责人是否该用户，即判断该用户是否部门负责人
					if(ud.getTbUser().getUId().equals(uid)){
						resultDept.add(ud);
					}
				}
			}
			
			List<DeptPeople> dps = new ArrayList<DeptPeople>();
			for(TbUserDept ud : resultDept){
				DeptPeople dp = new DeptPeople();
				dp.setId(ud.getTbUser().getUId());
				dp.setName(ud.getUdName());
				dp.setDeptID(ud.getUdId());
				dps.add(dp);
			}
			errMsg="1";
			deptPeoples = dps;
		}
		if(deptPeoples!=null){
			logger.info("the number of dept people:"+deptPeoples.size());
		}
		
		return "findUserDeptByDtId";
	}
	
	public String findDeptPeople(){
		
		if(isCurrentLeader()){
			errMsg = "1";
			peoples = null;
		} else {
			errMsg = "0";
			//获取其所属的部门人员
			peoples = taskDept.getUsersByDeptId(this.Did);
		}
		if(peoples!=null){
			logger.info("the number of peoples is :"+peoples.size());
		}
		
		return "findDeptPeople";
	}
	
	/**
	 * 返回下一层的部门和人
	 * @return
	 */
	public String findDeptAndPeoples(){
		try {
			depts = new ArrayList<SubDept>();
			logger.info("findDeptAndPeoples's udid： "+Did);
			
			List<UserDept> list = findDeptSer.findNextLevel(Did);
	        //使用新vo进行数据封装
			for(UserDept ud : list){
				SubDept sd = new SubDept();
				sd.setUdId(ud.getUdId());
				sd.setUdName(ud.getUdName());
				if(ud.getTbUser()!=null && ud.getTbUser().getUId()!=null){
					sd.setUId(ud.getTbUser().getUId());
				} else {
					sd.setUId(null);
				}
				depts.add(sd);
			}
			logger.info("the size of depts:"+depts.size());
			users = findDeptSer.findDeptsUsers(Did);
			logger.info("the size of users:"+users.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "findDeptAndPeoples";
	}
	
	/**
	 * 判断当前用户是否为指挥长或市局领导或稽查局的人员
	 * @return
	 */
	private boolean isCurrentLeader(){
		TbUser currentUser = this.pms.getCurrentUser(sessionMap);

		String uid = currentUser.getUId(); // 获取当前用户ID
		logger.info("Current userID:" + uid);
		boolean isLeader = false;
		// 根据传入的参数和当前用户的信息，判断当前用户是否为指挥长的角色
		logger.info(">>>looking for leader...");
		
		try {
			if(this.getSessionAttribute(EventUtil.PROCESSING_EVENT_ID)!=null){
				isLeader = identifyServ.isLeader(uid, getSessionAttribute(EventUtil.PROCESSING_EVENT_ID));
				if(isLeader){
					return isLeader;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			errMsg = "操作失败！请重试...";
			return false;
		}
		logger.info(">>>Can not find a leader!");
		logger.info(">>>finding ViceLeader...");
		
		isLeader = identifyServ.isCenterDeptPeople(uid, "DI0100000000");
		if(isLeader){
			return isLeader;
		} else {
			isLeader = identifyServ.isCenterDeptPeople(uid, "DI0123000000");
			if(isLeader){
				return isLeader;
			}
		}
		return false;
	}
	


	public String queryDeptIdbyTid(){
		TbTask tt = taskDAo.findTaskDetailById(tid);
		if(tt != null){
			DeptPeople dp = new DeptPeople();
			dp.setDeptID(tt.getTbUserDept().getUdId());
			dp.setId(tt.getTbUser().getUId());
			deptpeople = dp;
			errMsg = "0";
			return "getDeptIdByTid";
		} else {
			errMsg = "1";
			return "getDeptIdByTid_false";
		}		
	}
	
	/**
	 * 获取部门信息的入口方法，方法里包括用户信息和事件信息都的判别
	 * */
	/*
	public String getDepts() {

		TbUser currentUser = this.pms.getCurrentUser(sessionMap);
		String uid = currentUser.getUId();
		
		Set<TbUserDept> userDepts = currentUser.getTbUserDepts(); // 取出当前用户所属的部门，一个用户可能同时属于多个部门，但只能是一个部门的负责人

		if (userDepts != null) {
			for (TbUserDept dept : userDepts) {
				logger.info("searching Dept ID:" + dept.getUdId());
				TreeNode tn = lts.getTreeNodeById(dept.getUdId());

				UserDeptContact udc = ((UserDept) tn.getBindData()).getTbUser();

				if (udc != null) {
					String deptLeaderId = udc.getUId(); // 从部门树中获取部门的负责人
					if (deptLeaderId.equals(uid)) { // 匹配用户所属的部门的负责人是否该用户，即判断该用户是否部门负责人
						logger.info("------It is Dept Leader,id:"+ deptLeaderId);
						int n = taskDept.getSubDeptsById(dept.getUdId()).size();
						logger.info("------Sub dept length:" + n);
						if (n > 0) {
							this.deptInfos = taskDept.getSubDepts(dept.getUdId()); // 根据用户负责的部门ID查询其属下的部门
							break;
						} else { // 如果该用户所负责的部门没有子部门，获取其所属的部门人员
							peoples = taskDept.getUsersByDeptId(dept.getUdId());
							if (peoples != null) {
								break;
							} else {
								errMsg = "找不到部门的所属人员，请与系统管理员联系...";
								return "getDepts_fail";
							}

						}
					}
				}
			}
		} else {
			getOK = false;
		}

		if (getOK) {
			return "getDepts";
		} else {
			errMsg = "找不到当前用户所属的部门信息，请与系统管理员联系...";
			return "getDepts_fail";
		}

	}
	*/


	// 以下是属性的get，set方法

	public TbUser getTbUser() {
		return tbUser;
	}

	public List<DeptInfo> getDeptInfos() {
		return deptInfos;
	}

	public Map<String, String> getDeptOption() {
		return deptOption;
	}

	public void setDeptOption(Map<String, String> deptOption) {
		this.deptOption = deptOption;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}

	public List<DeptPeople> getPeoples() {
		return peoples;
	}

	public void setPeoples(List<DeptPeople> peoples) {
		this.peoples = peoples;
	}
	public GetDeptInTask getTaskDept() {
		return taskDept;
	}

	public void setTaskDept(GetDeptInTask taskDept) {
		this.taskDept = taskDept;
	}
	public String getDtId() {
		return dtId;
	}

	public void setDtId(String dtId) {
		this.dtId = dtId;
	}
	
	public String getDid() {
		return Did;
	}

	public void setDid(String did) {
		Did = did;
	}

	public List<TbDeptType> getDeptTypes() {
		return deptTypes;
	}

	public void setDeptTypes(List<TbDeptType> deptTypes) {
		this.deptTypes = deptTypes;
	}
	
	public List<TbUserDept> getUserDepts() {
		return userDepts;
	}

	public void setUserDepts(List<TbUserDept> userDepts) {
		this.userDepts = userDepts;
	}
	
	public List<DeptPeople> getDeptPeoples() {
		return deptPeoples;
	}

	public void setDeptPeoples(List<DeptPeople> deptPeoples) {
		this.deptPeoples = deptPeoples;
	}
	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	public DeptPeople getDeptpeople() {
		return deptpeople;
	}

	public void setDeptpeople(DeptPeople deptpeople) {
		this.deptpeople = deptpeople;
	}

	public List<SubDept> getDepts() {
		return depts;
	}

	public void setDepts(List<SubDept> depts) {
		this.depts = depts;
	}

	public List<UserDeptContact> getUsers() {
		return users;
	}

	public void setUsers(List<UserDeptContact> users) {
		this.users = users;
	}
}
